<?php

namespace app\admin\controller;

use app\common\logic\UserLogic;
use app\common\model\User as UserModel;
use app\common\services\MoneyAccount;
use PHPExcel;
use think\exception\Handle;

class User extends Common
{
//    public function index()
//    {
//        $num = [100,107,106];
//        foreach ($num as $k=>$v){
//
//             $a[] = db('test')->where('learn','>=',$v)->select();
//        }
//        halt($a);
//
//
//    }

    //用户列表
    public function index()
    {
        $user = new UserLogic;
        if (is_post()) {
            $rst = model('User')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                return ['code' => 1, 'msg' => '修改成功', 'data' => $rst,];
            }
        }
        if (input('get.over_sort')) {
            $num = input('get.over_sort');
            if ($num == 1) {
                $this->order = 'us_all_get desc';
            }
            if ($num == 2) {
                $this->order = 'us_all_get asc';
            }
        }
        if (input('get.userid')) {
            $uid = input('get.userid');
            $pid = db('user')->where('id', $uid)->value('us_pid');
            $this->map[] = ['id', '=', $pid];
        }
        if (input('get.id')) {
            $this->map[] = ['id', '=', input('get.id')];
        }
        if (input('get.tel_id')) {
            $tel_id = input('get.tel_id');
            if (strlen($tel_id) == 11) {
                $tel = db('user')->where('us_tel', '=', $tel_id)->value('id');
                $pid = db('user')->where('us_pid', '=', $tel)->column('id');
            } else {
                $pid = db('user')->where('us_pid', '=', $tel_id)->column('id');
            }
            $this->map[] = ['id', 'in', $pid];
        }
        if (input('get.keywords')) {
            $this->map[] = ['us_tel|us_account|us_nickname', 'like', '%' . input('get.keywords') . '%'];
        }
        if (is_numeric(input('get.us_type'))) {
            $this->map[] = ['us_type', '=', input('get.us_type')];
        }
        if (is_numeric(input('get.paiming'))) {
            $this->map[] = ['us_type', '=', input('get.us_type')];
        }
        if (is_numeric(input('get.gave_status'))) {
            $this->map[] = ['gave_status', '=', input('get.gave_status')];
        }
        $this->map[] = ['us_delete_status', '=', 1];
        $list = $user->getList($this->map, $this->order, $this->size);
        foreach ($list as $k => $value) {
            $a[$k] = model('User')->where('us_pid', $value['id'])->column('id');
            $list[$k]['us_pid_num'] = count($a[$k]);
            $list[$k]['us_pid_tel'] = model('User')->where('id', $value['us_pid'])->value('us_tel');
        }
        $this->assign('list', $list);
        return $this->fetch();
    }

    // 更改会员介绍，并作记录
    public function changeUsType()
    {
        // 1 会员 2 店主 3 运营中心  变更运营中心记录之前父id ,并统计业绩  2 .运营中心变更会员或者店主 把之间fid 在添加回去，业绩删除

        if (is_post()) {
            $time = date('Y-m-d H:i:s');
            $uid = input('post.id');
            // 查询更改会员的身份
            $editUserType = model('user')->where('id',$uid)->value('us_type');

            // 更改角色
            if (input('post.value')==3){

                // 获取该用户的所有下级，用于计算分离前业绩
                $usInfo = model('User')->where('id',$uid)->find();
                $teams =  $this->getAllChildrenId($uid);
                array_unshift ($teams,$uid);
                $teamMoney = model('MoneyDetailed')
                    ->whereIn('us_id',$teams)->sum('money');


                $up = model('User')->where('id',$uid)
                    ->update(['yun_yuan_pid'=>$usInfo['us_pid'],'yun_yuan_yeji'=>$teamMoney,'us_pid'=>0,'cheng_yun_time'=>$time]);

                // 确认修改会员身份
                $rst = model('User')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
                $this->changLog($uid,$editUserType,input('post.value'));
                if ($rst && $up) {
                    return ['code' => 1, 'msg' => '修改成功', 'data' => $rst,];
                }
            }else{
                // 查看是否存在 运营中心原业绩和运营中心原ID
                $check = model('user')->where('id',$uid)->find();


                if (!empty($check['yun_yuan_pid'])){

                    model('User')->where('id',$uid)
                        ->update(['us_pid'=>$check['yun_yuan_pid'],'yun_yuan_pid'=>0,'yun_yuan_yeji'=>0]);
                }
                $this->changLog($uid,$editUserType,input('post.value'));
                $rst = model('User')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
                if ($rst) {
                    return ['code' => 1, 'msg' => '修改成功', 'data' => $rst,];
                }
            }

        }

    }

    // 记录会员变更操作记录
    private function changLog($us_id,$us_y_type,$us_type)
    {
        $us_pid = db('user')->where('id',$us_id)->value('us_pid');
        // 操作人信息
        $adminInfo = session('admin');
        $info = [
            'admin_user_id'=>$adminInfo['id'],
//            'edit_order_num'=>$or_num,
            'admin_user_name'=>$adminInfo['ad_name'],
            'admin_user_phone'=>$adminInfo['ad_tel'],
            'admin_user_identity'=>$adminInfo['ro_id'],
            'type'=>3,
            'edit_user_y_type'=>$us_y_type,
            'edit_user_type'=>$us_type,
            'edit_user_pid'=>$us_pid,
            'edit_user_id'=>$us_id,
            'edit_time'=>date('Y-m-d H:i:s'),
            'content'=>'角色变更'
        ];
        model('Recording')->insert($info);
    }


    //用户界面上的状态修改
    public function change()
    {
        if (is_post()) {
            $rst = model('User')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                return ['code' => 1, 'msg' => '修改成功', 'data' => $rst,];
            }
        }
    }


    /**
     * 新进会员
     */
    public function news()
    {
        $user = new UserLogic;
        if (is_post()) {
            $rst = model('User')->editInfo([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                return [
                    'code' => 1,
                    'msg' => '修改成功',
                    'data' => $rst,
                ];
            }
        }
        if (input('get.keywords')) {
            $this->map[] = ['us_tel|us_account|us_nickname', '=', input('get.keywords')];
        }
        $this->map[] = ['us_delete_status', '=', 1];
        $this->map[] = ['ca_id', 'neq', ''];
        $this->order = 'us_apply_time desc';
        $list = $user->getList($this->map, $this->order, $this->size);
        $this->assign(array(
            'yuming' => $_SERVER['HTTP_HOST'],
            'list' => $list,
        ));
        return $this->fetch();

    }

    /**
     * 新进会员
     */
    public function register()
    {
        $user = new UserLogic;
        if (input('get.keywords')) {
            $this->map[] = ['us_tel|us_account|us_nickname', '=', input('get.keywords')];
        }
        $this->map[] = ['us_delete_status', '=', 1];
        $this->map[] = ['qrcode_ca_id', 'neq', ''];
        $list = $user->getList($this->map, $this->order, $this->size);
        foreach ($list as $k => $v) {
            $v['ptel'] = model("User")->where('id', $v['us_pid'])->value('us_tel');
            $v['p_nickname'] = model("User")->where('id', $v['us_pid'])->value('us_nickname');
        }
        $this->assign(array(
            'yuming' => $_SERVER['HTTP_HOST'],
            'list' => $list,
        ));
        return $this->fetch();

    }


    /**
     * 删除用户
     */
    public function delete()
    {
        if (empty(input('post.id'))) {
            $this->error('id不存在');
        }
        $id = input('post.id');
        $user = model('User')->where('id', $id)->find();
        $new_p['us_pid'] = $user['us_pid'];
        $new_p['us_path'] = $user['us_path'];
        $children = model('User')->where('us_pid', $id)->select();
        foreach ($children as $k => $v) {
            model('User')->where('id', $v['id'])->update($new_p);
        }
        $re = model('User')->where('id', $id)->delete();
        $rel = array();
        if ($re) {
            $rel['msg'] = '删除成功！';
        } else {
            $rel['msg'] = '该用户已被删除！';
        }
        return $rel;
    }

    /**
     * 修改用户
     * @return mixed
     */
    public function edit()
    {
        if (is_post()) {
            $data = input('post.');
            $userlogic = new UserLogic;
            $rel = $userlogic->edit($data);
            if ($rel['code'] = 1) {
                $this->success($rel['msg']);
            } else {
                $this->error($rel['msg']);
            }
            return $rel;
        }
        $usermodel = new UserModel;
        $info = $usermodel->getInfo(input('get.id'));
        $info['select_tel'] = \db('user')->column('us_tel');
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 修改用户
     */
    public function detail()
    {
        $usermodel = new UserModel;
        $info = $usermodel->getInfo(input('get.id'));
        //halt($info);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        if (is_post()) {
            $userlogic = new UserLogic;
            $rel = $userlogic->addUser(input('post.'));
            return json($rel);
        }
//        $list = model('Cate')->select();
//        $this->assign('catelist',$list);
        return $this->fetch();
    }


    /**
     * 地址列表
     */
    public function addr()
    {
        if (is_post()) {
            $rst = model('User_addr')->xiugai([input('post.key') => input('post.value')], ['id' => input('post.id')]);
            if ($rst) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
            return $rst;
        }
        if (input('get.id')) {
            $this->map[] = ['us_id', '=', input('get.id')];
        } else {
            $this->error("非法操作");
        }
        $list = model('User_addr')->chaxun($this->map, $this->order, $this->size);
        $this->assign(array(
            'list' => $list,
            'name' => model('User')->where('id', input('get.id'))->value('us_account'),
        ));
        return $this->fetch();
    }

    /**
     * 获取推荐人姓名
     */
    public function confirmP()
    {
        $ptel = input('post.ptel');
        $name = model('User')->where(['us_type' => [2, 3]])->where('us_tel', $ptel)->value('us_nickname');
        if ($name) {
            return ['code' => 1, 'msg' => $name];
        } else {
            return ['code' => 0, 'msg' => '推荐人不可推荐'];
        }
    }

    /**
     * 我的团队，树状图
     */
    public function showMyteam($id)
    {

        $list = db('user')->where('us_pid', $id)->select();
        $this->assign('list', $list);
        $id = input('id');
        $data = db('user')->where('id', $id)->find();

        if ($data['us_type'] == 0) {
            $data['us_type'] = '非激活会员';
        } elseif ($data['us_type'] == 1) {
            $data['us_type'] = '会员';
        } elseif ($data['us_type'] == 2) {
            $data['us_type'] = '店主';
        } elseif ($data['us_type'] == 3) {
            $data['us_type'] = '运营中心';
        }
        $data['count'] = db('user')->where('us_pid', $id)->count();

        $data['over'] = db('wallet')->where('wallet_type', null)->where('us_id', $id)->sum('wa_num');
        $array = json_encode(getMyTeam($id));
        $this->assign(['data' => $data]);
        $this->assign(['array' => $array]);
        return $this->fetch();


    }

    /**
     * 会员账户明细
     */
    public function myAccount()
    {
        $id = input('get.id');

        //  1.消费 2.提现 3.推荐收益 4.后台充值 5.供应商所得消费奖励
        $infos = model('MoneyDetailed')
            ->where('us_id', $id)
            ->paginate(10, false, $config = ['query' => request()->param()]);

        //  累计消费
        $xiaofei =  model('MoneyDetailed')->where('us_id', $id)
                  ->where('type', 1)
                  ->sum('money');

        //  累计提现
        $tixian = model('MoneyDetailed')
            ->where('us_id', $id)
            ->where('tx_people_role',1)
            ->where('type', 3)->sum('money');
        //  推荐收益
        $teamMoney = model('MoneyDetailed')
            ->where('us_id', $id)
            ->where('type', 2)->sum('money');

        // 交易金额
        $Money =$xiaofei+$tixian+$teamMoney;
        $this->assign([
            'list' => $infos,
            'xiaofei' => $xiaofei,
            'tixian' => $tixian,
            'teamMoney' => $teamMoney,
            'payMoney'=>  $Money
        ]);

        return $this->fetch();
    }


    /**
     * 更改会员角色
     */
    public function roleChange()
    {
        $id = input('get.id');
        $this->map[] = ['us_type', '=', 2];
        $field = ['id', 'us_account', 'us_tel', 'us_nickname'];
        $list = model('User')->getList($this->map, $this->order, $this->size, $field);
        $this->assign(['list' => $list, 'id' => $id]);
        return $this->fetch();
    }

    /**
     * 获取所选加盟店id
     */
    public function getJoinId()
    {
        $id = input('post.id');
        $did = input('post.did');
        $list = model('User')->where('us_type', '=', 2)->whereIn('id', $id)->update(['us_type_operator' => $did]);
        if ($list) {
            return ['msg' => '选择成功', 'code' => 200];
        }
    }

    public function excel()
    {//导出Excel
        $xlsName = "所有会员列表";
        $xlsCell = array(
            array('us_account', '账户名'),
            array('us_nickname', '姓名'),
            array('us_tel', '手机号'),
            array('us_pid', '推荐人'),
            array('merchant_status', '类型'),
            array('us_level', '会员级别'),
            array('us_abc', '商品分类'),
            array('us_shop_bi', '现金积分'),
            array('us_shop_quan', '消费积分'),
            array('us_award_type', '结算法'),
            array('us_add_time', '添加时间'),
        );
        $xlsData = array();
        // halt($info['list']);
        $info = model('User')->field('us_account,us_nickname,us_tel,us_pid,merchant_status,us_level,us_abc,us_shop_bi,us_shop_quan,us_award_type,us_add_time')->select();
        foreach ($info as $k => $v) {
            $info[$k]['us_pid'] = model('User')->where('id', $v['us_pid'])->value('us_nickname');
            if ($v['merchant_status'] == 2) {
                $info[$k]['merchant_status'] = '商家';
            } else {
                $info[$k]['merchant_status'] = '会员';
            }
            if ($v['us_level'] == 0) {
                $info[$k]['us_level'] = '普通会员';
            } elseif ($v['us_level'] == 2) {
                $info[$k]['us_level'] = '一星会员';
            } elseif ($v['us_level'] == 4) {
                $info[$k]['us_level'] = '二星会员';
            } elseif ($v['us_level'] == 6) {
                $info[$k]['us_level'] = '三星会员';
            }
            if ($v['us_abc'] == 1) {
                $info[$k]['us_abc'] = 'A类';
            } elseif ($v['us_abc'] == 2) {
                $info[$k]['us_abc'] = 'B类';
            } elseif ($v['us_abc'] == 3) {
                $info[$k]['us_abc'] = 'C类';
            }
            if ($v['us_award_type'] == 1) {
                $info[$k]['us_award_type'] = '全额';
            } elseif ($v['us_award_type'] == 0.5) {
                $info[$k]['us_award_type'] = '半价';
            } elseif ($v['us_award_type'] == 0) {
                $info[$k]['us_award_type'] = '免费';
            }
            // $xlsData[$k]['or_pd_price'] = $v['or_pd_price'];
            // $xlsData[$k]['or_pd_num'] = $v['or_pd_num'];
            // $xlsData[$k]['or_pd_content'] = $v['or_pd_content'];
            // $xlsData[$k]['pd_color'] = $v['pd_color'];
            // $xlsData[$k]['pd_spec'] = $v['pd_spec'];
        }
        // halt($xlsData);
        $this->exportExcel($xlsName, $xlsCell, $info);
    }

    function exportExcel($expTitle, $expCellName, $expTableData)
    {
        //include_once EXTEND_PATH.'PHPExcel/PHPExcel.php';//方法二
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $num = $dataNum + 3;
        $objPHPExcel = new PHPExcel();//方法一
        //$objPHPExcel = new \PHPExcel();//方法二
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->getActiveSheet(0)->mergeCells('A' . $num . ':' . $cellName[$cellNum - 1] . $num);//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  表格生成时间:' . date('Y-m-d H:i:s'));
        // halt($num);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $num, '制表人:                      ' . '会计：                      ' . '出纳：                      ' . '审核：                      ');
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
        exit;
    }

}